#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
班级模型
"""

from datetime import datetime
from sqlalchemy import Column, Integer, String, DateTime, Text, ForeignKey, Table
from sqlalchemy.orm import relationship
from .base import Base

# 班级-学生关联表
class_student = Table(
    'class_student',
    Base.metadata,
    Column('class_id', Integer, ForeignKey('classes.id'), primary_key=True),
    Column('student_id', Integer, ForeignKey('users.id'), primary_key=True)
)

class Class(Base):
    """班级模型"""
    __tablename__ = 'classes'
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(100), nullable=False, comment='班级名称')
    description = Column(Text, comment='班级描述')
    teacher_id = Column(Integer, ForeignKey('users.id'), nullable=False, comment='班主任ID')
    max_students = Column(Integer, default=50, comment='最大学生数')
    status = Column(String(20), default='active', comment='班级状态：active/inactive')
    created_at = Column(DateTime, default=datetime.now, comment='创建时间')
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    # 关联关系
    teacher = relationship('User', foreign_keys=[teacher_id], back_populates='managed_classes')
    students = relationship('User', secondary=class_student, back_populates='enrolled_classes')
    assignments = relationship('Assignment', back_populates='class_obj', cascade='all, delete-orphan')
    
    def __repr__(self):
        return f'<Class {self.name}>'
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'name': self.name,
            'description': self.description,
            'teacher_id': self.teacher_id,
            'teacher_name': self.teacher.name if self.teacher else None,
            'max_students': self.max_students,
            'current_students': len(self.students),
            'status': self.status,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
    
    def to_dict_with_students(self):
        """转换为包含学生信息的字典"""
        data = self.to_dict()
        data['students'] = [student.to_dict() for student in self.students]
        return data
